<?php

namespace App\Jobs;

use App\Models\Common\Wechat;
use App\Models\Shop;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ExploreRefundJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $refund_id; // 退款id

    /**
     * Create a new job instance.
     *
     * @param int $refund_id
     * @return void
     */
    public function __construct($refund_id)
    {
        $this->refund_id = $refund_id;
    }

    /**
     * Execute the job.
     * 退款
     *
     * @return void
     */
    public function handle()
    {
        try{
            // 查询退款单
            $refund = DB::table('laifei_refund')->where('refund_id','=',$this->refund_id)->first();
            $refund = json_decode(json_encode($refund), true);

            // 查询订单余额
            $order = DB::table('laifei_orders')->where('order_id', '=', $refund['order_id'])->first();
            $order = json_decode(json_encode($order), true);

            // 检查订单余额是否足够
            if($refund['refund_fee'] > ((int)($order['total_fee'] * 100) - (int)($order['refund_fee']* 100))){
                Log::error('剩余金额不足',[$refund['refund_fee'],((int)($order['total_fee'] * 100) - (int)($order['refund_fee']* 100))]);
                // 记录为退款失败
                self::fail($refund['apply_id']);
                return;
            }

            if($refund['num'] > $order['num']-$order['refund_num']){
                Log::error('剩余单量不足');
                // 记录为退款失败
                self::fail($refund['apply_id']);
                return;
            }

            // 检查完毕开始退款
            $app = Wechat::payment();
            $refund_message = [$order['trade_no'], $refund['refund_number'], (int)($order['total_fee'] * 100), $refund['refund_fee'], [
                // 可在此处传入其他参数，详细参数见微信支付文档
                'refund_desc' => '用户申请退款',
                'notify_url' => env('APP_URL').'/api/wechat/refund/success', // 回调接口
            ]];
//        $app->refund->byOutTradeNumber(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []);
            $result = $app->refund->byOutTradeNumber(...$refund_message);
            Log::debug('用户退款',['refund_message'=>$refund_message,'result_message'=>$result]);
            if($result['result_code'] === 'SUCCESS'){// 退款申请成功
                // 修改当前退款订单状态
                self::success($refund['apply_id']);
            } else {// 退款失败
                // 修改退款单状态
                self::fail($refund['apply_id']);
            }
            return;
        }catch (\Exception $e){
            Log::error(ExploreRefundJob::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
        }
        return;
    }


    /**
     * 退款申请成功
     * @param $apply_id
     */
    private function success($apply_id){
        DB::table('laifei_refund')->where('refund_id','=',$this->refund_id)->update([
            'status'=>1,//正在申请退款
        ]);
        Shop::applyFinish($apply_id);
        return;
    }

    /**
     * 退款申请失败
     * @param $apply_id
     */
    private function fail($apply_id){
        DB::table('laifei_refund')->where('refund_id','=',$this->refund_id)->update([
            'status'=>3,//退款失败
        ]);
        Shop::applyFinish($apply_id);
        return;
    }

}
